package com.xiyan.mq.receiver;

import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;

import java.io.IOException;

/**
 * @author: ruiyanglee
 * @date: 2020-11-09 14:59
 * @description:
 */
// 指定监听的队列
public class Tut2Receiver {
    public static final Logger log = LoggerFactory.getLogger(Tut2Receiver.class);

    // 如果消息没被消费则将其删除
    @RabbitListener(queues = {"MQ-KEY"})
    public void receiverA(Message message, Channel channel) throws IOException {
        String msg = new String(message.getBody());
        log.info("收到业务消息A：{}",msg);
        boolean ack = true;
        Exception exception = null;
        try{
            // 如果消息发生异常，直接抛出异常并告知queue不要删除这条消息，并将重新发送消费
            if (msg.contains("dead letter")){
                throw new RuntimeException("dead letter exception");
            }
        }catch (Exception e){
            ack = false;
            exception = e;
        }
        if (!ack){
            log.error("消息消费发生异常，error msg:{}", exception.getMessage(), exception);
            // 将信息重新放回到队列中
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,false);
        }else{
            // 取值为false时，表示通知 RabbitMQ 当前消息被确
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }
    }

    /**
     * 业务B队列消费代码
     */
//    @RabbitListener(queues = {"MQ-LOG"})
//    public void receiverB(Message message, Channel channel) throws IOException {
//        String msg = new String(message.getBody());
//        log.info("收到业务消息B：{}",msg);
//        // 手动消息确认步骤 配合acknowledge-mode: manual 模式
//        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
//    }
}
